// pages/documents/documents.js
Page({
  data: {
    documents: [],
    loading: true,
    currentTab: 0,
    tabs: [
      { key: 'all', name: '全部' },
      { key: 'PENDING', name: '待审核' },
      { key: 'APPROVED', name: '已通过' },
      { key: 'REJECTED', name: '已拒绝' }
    ],
    page: 1,
    pageSize: 10,
    hasMore: true,
    refreshing: false
  },

  onLoad() {
    this.loadDocuments();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore();
    }
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index,
      page: 1,
      documents: [],
      hasMore: true
    });
    this.loadDocuments();
  },

  // 加载文档列表
  loadDocuments() {
    this.setData({ loading: true });

    const token = wx.getStorageSync('token');
    if (!token) {
      this.showLoginPrompt();
      return;
    }

    const currentStatus = this.data.tabs[this.data.currentTab].key;
    const params = {
      page: this.data.page,
      size: this.data.pageSize
    };

    if (currentStatus !== 'all') {
      params.status = currentStatus;
    }

    const queryString = Object.keys(params)
      .map(key => `${key}=${params[key]}`)
      .join('&');

    wx.request({
      url: `http://localhost:8080/api/user/documents?${queryString}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const newDocuments = res.data.data.content || [];
          this.setData({
            documents: this.data.page === 1 ? newDocuments : [...this.data.documents, ...newDocuments],
            hasMore: !res.data.data.last,
            loading: false,
            refreshing: false
          });
        } else {
          this.showError(res.data.message || '加载失败');
        }
      },
      fail: () => {
        // 模拟数据
        const mockDocuments = this.generateMockDocuments();
        const filteredDocuments = this.filterDocumentsByStatus(mockDocuments, currentStatus);
        
        this.setData({
          documents: this.data.page === 1 ? filteredDocuments : [...this.data.documents, ...filteredDocuments],
          hasMore: false,
          loading: false,
          refreshing: false
        });
      },
      complete: () => {
        wx.stopPullDownRefresh();
      }
    });
  },

  // 生成模拟文档数据
  generateMockDocuments() {
    return [
      {
        id: 1,
        documentType: 'ID_CARD',
        fileName: '身份证正面.jpg',
        fileSize: 1024000,
        status: 'APPROVED',
        uploadTime: '2024-01-10 14:30:00',
        auditTime: '2024-01-10 16:20:00',
        auditComment: '审核通过',
        fileUrl: '/temp/id_card_front.jpg'
      },
      {
        id: 2,
        documentType: 'ID_CARD',
        fileName: '身份证反面.jpg',
        fileSize: 980000,
        status: 'APPROVED',
        uploadTime: '2024-01-10 14:32:00',
        auditTime: '2024-01-10 16:20:00',
        auditComment: '审核通过',
        fileUrl: '/temp/id_card_back.jpg'
      },
      {
        id: 3,
        documentType: 'EDUCATION',
        fileName: '学历证明.pdf',
        fileSize: 2048000,
        status: 'PENDING',
        uploadTime: '2024-01-15 10:15:00',
        auditTime: null,
        auditComment: null,
        fileUrl: '/temp/education.pdf'
      },
      {
        id: 4,
        documentType: 'WORK_EXPERIENCE',
        fileName: '工作证明.pdf',
        fileSize: 1536000,
        status: 'REJECTED',
        uploadTime: '2024-01-12 09:20:00',
        auditTime: '2024-01-12 15:30:00',
        auditComment: '文档不清晰，请重新上传',
        fileUrl: '/temp/work_experience.pdf'
      },
      {
        id: 5,
        documentType: 'SKILL_CERTIFICATE',
        fileName: '技能证书.jpg',
        fileSize: 1200000,
        status: 'APPROVED',
        uploadTime: '2024-01-08 16:45:00',
        auditTime: '2024-01-09 10:30:00',
        auditComment: '证书有效，审核通过',
        fileUrl: '/temp/skill_cert.jpg'
      }
    ];
  },

  // 根据状态过滤文档
  filterDocumentsByStatus(documents, status) {
    if (status === 'all') {
      return documents;
    }
    return documents.filter(doc => doc.status === status);
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      documents: [],
      hasMore: true,
      refreshing: true
    });
    this.loadDocuments();
  },

  // 加载更多
  loadMore() {
    this.setData({
      page: this.data.page + 1
    });
    this.loadDocuments();
  },

  // 预览文档
  previewDocument(e) {
    const doc = e.currentTarget.dataset.doc;
    
    if (this.isImageFile(doc.fileName)) {
      wx.previewImage({
        current: doc.fileUrl,
        urls: [doc.fileUrl]
      });
    } else {
      wx.showModal({
        title: '文档预览',
        content: '暂不支持此类型文档的预览，是否下载？',
        confirmText: '下载',
        success: (res) => {
          if (res.confirm) {
            this.downloadDocument(doc);
          }
        }
      });
    }
  },

  // 下载文档
  downloadDocument(doc) {
    wx.showLoading({
      title: '下载中...'
    });

    // 模拟下载
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '下载成功',
        icon: 'success'
      });
    }, 1500);
  },

  // 删除文档
  deleteDocument(e) {
    e.stopPropagation();
    const docId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此文档吗？删除后无法恢复。',
      success: (res) => {
        if (res.confirm) {
          this.performDeleteDocument(docId);
        }
      }
    });
  },

  // 执行删除文档
  performDeleteDocument(docId) {
    const token = wx.getStorageSync('token');

    wx.showLoading({
      title: '删除中...'
    });

    wx.request({
      url: `http://localhost:8080/api/user/documents/${docId}`,
      method: 'DELETE',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          this.removeDocumentFromList(docId);
        } else {
          wx.showToast({
            title: res.data.message || '删除失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        this.removeDocumentFromList(docId);
      }
    });
  },

  // 从列表中移除文档
  removeDocumentFromList(docId) {
    const documents = this.data.documents.filter(doc => doc.id !== docId);
    this.setData({ documents });
  },

  // 重新上传文档
  reuploadDocument(e) {
    e.stopPropagation();
    const docType = e.currentTarget.dataset.type;
    
    wx.navigateTo({
      url: `/pages/upload-document/upload-document?type=${docType}&reupload=true`
    });
  },

  // 上传新文档
  uploadDocument() {
    wx.navigateTo({
      url: '/pages/upload-document/upload-document'
    });
  },

  // 显示登录提示
  showLoginPrompt() {
    wx.showModal({
      title: '未登录',
      content: '请先登录后查看文档信息',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          });
        }
      }
    });
  },

  // 显示错误信息
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none'
    });
    this.setData({
      loading: false,
      refreshing: false
    });
  },

  // 判断是否为图片文件
  isImageFile(fileName) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
    const extension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'));
    return imageExtensions.includes(extension);
  },

  // 格式化文档类型
  formatDocumentType(type) {
    const typeMap = {
      'ID_CARD': '身份证',
      'EDUCATION': '学历证明',
      'WORK_EXPERIENCE': '工作经历',
      'SKILL_CERTIFICATE': '技能证书',
      'HEALTH_CERTIFICATE': '健康证',
      'OTHER': '其他'
    };
    return typeMap[type] || type;
  },

  // 格式化文档状态
  formatDocumentStatus(status) {
    const statusMap = {
      'PENDING': '待审核',
      'APPROVED': '已通过',
      'REJECTED': '已拒绝'
    };
    return statusMap[status] || status;
  },

  // 格式化文件大小
  formatFileSize(size) {
    if (size < 1024) {
      return size + 'B';
    } else if (size < 1024 * 1024) {
      return Math.round(size / 1024) + 'KB';
    } else {
      return Math.round(size / (1024 * 1024)) + 'MB';
    }
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'PENDING': '#fa8c16',
      'APPROVED': '#52c41a',
      'REJECTED': '#f5222d'
    };
    return colorMap[status] || '#666';
  },

  // 获取文档图标
  getDocumentIcon(fileName, documentType) {
    if (this.isImageFile(fileName)) {
      return '/images/image-file.png';
    } else if (fileName.toLowerCase().endsWith('.pdf')) {
      return '/images/pdf-file.png';
    } else {
      return '/images/document-file.png';
    }
  }
});
